<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>智慧大棚系统 - 投入管理</title>
		<script src="https://cdn.tailwindcss.com"></script>
		<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.7.2/css/all.min.css" rel="stylesheet">
		<script src="https://cdn.jsdelivr.net/npm/vue@3.3.11/dist/vue.global.prod.min.js"></script>
		<script src="https://cdn.jsdelivr.net/npm/axios@1.7.7/dist/axios.min.js"></script>

		<!-- Tailwind配置 -->
		<script>
			tailwind.config = {
				theme: {
					extend: {
						colors: {
							primary: '#2E7D32',
							secondary: '#1976D2',
							accent: '#F59E0B',
							neutral: {
								100: '#F9FAFB',
								200: '#F3F4F6',
								300: '#E5E7EB',
								400: '#D1D5DB',
								500: '#9CA3AF',
								600: '#6B7280',
								700: '#4B5563',
								800: '#1F2937',
								900: '#111827'
							}
						},
						fontFamily: {
							inter: ['Inter', 'sans-serif'],
						},
						boxShadow: {
							'card': '0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06)',
							'card-hover': '0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05)',
						}
					},
				}
			}
		</script>

		<style type="text/tailwindcss">
			@layer utilities {
            .management-title {
                @apply text-xl font-bold text-neutral-800 mb-4 border-b border-neutral-200 pb-2;
            }
            .search-input {
                @apply px-3 py-2 border border-neutral-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary transition-all duration-200;
            }
            .dropdown {
                @apply relative;
            }
            .dropdown-button {
                @apply px-4 py-2 border border-neutral-300 rounded-md flex items-center justify-between w-full bg-white;
            }
            .dropdown-content {
                @apply absolute mt-1 w-full bg-white rounded-md shadow-md z-10 max-h-60 overflow-y-auto;
            }
            .dropdown-item {
                @apply px-4 py-2 hover:bg-primary/10 cursor-pointer;
            }
            .button {
                @apply px-4 py-2 bg-primary text-white rounded-md hover:bg-primary/90 transition-colors duration-200;
            }
            .editButton {
                @apply bg-blue-600 hover:bg-blue-700;
            }
            .deleteButton {
                @apply bg-red-600 hover:bg-red-700;
            }
            .investButton {
                @apply bg-green-600 hover:bg-green-700;
            }
            .investedButton {
                @apply bg-gray-500 cursor-not-allowed;
            }
            table {
                @apply w-full border-collapse;
            }
            th {
                @apply px-4 py-2 bg-neutral-100 text-left text-xs font-medium text-neutral-600 uppercase tracking-wider border border-neutral-200;
            }
            td {
                @apply px-4 py-2 border border-neutral-200;
            }
            dialog {
                @apply fixed inset-0 m-auto w-1/2 max-w-md p-6 rounded-lg shadow-xl z-50 bg-white border-none;
            }
            dialog::backdrop {
                @apply bg-black/50 backdrop-blur-sm;
            }
            .sidebar {
                @apply w-64 bg-white border-r border-neutral-200 h-screen fixed left-0 top-0 pt-20 overflow-y-auto;
            }
            .header {
                @apply bg-white shadow-md fixed w-full z-50 h-20 flex items-center px-6;
            }
            .content {
                @apply ml-64 pt-20 px-6 pb-10;
            }
            .sidebar-item {
                @apply block py-3 px-4 text-neutral-700 hover:bg-primary/10 hover:text-primary transition-colors duration-200 border-l-4 border-transparent;
            }
            .sidebar-item.active {
                @apply bg-primary/10 text-primary border-primary;
            }
        }
    </style>
	</head>
	<body>
		<div id="app">
			<div class="header">
				<div class="bg-primary text-white p-2 rounded-lg">
					<i class="fa-solid fa-farm text-xl"></i>
				</div>
				<h1 class="text-xl font-bold text-neutral-800 ml-2">智慧大棚管理系统</h1>
			</div>

			<div class="container">
				<div class="sidebar">
					<ul>
						<li><a href="/greenhouse/GreenHouseType/list.html" class="sidebar-item">大棚种类管理</a></li>
						<li><a href="/greenhouse/GreenHouseLocation/list.html" class="sidebar-item">大棚位置管理</a></li>
						<li><a href="/greenhouse/GreenHouse/list.html" class="sidebar-item">大棚管理</a></li>
						<li><a href="/greenhouse/Crops/list.html" class="sidebar-item">农产品管理</a></li>
						<li><a href="/greenhouse/PlanType/list.html" class="sidebar-item">计划分类管理</a></li>
						<li><a href="/greenhouse/Plan/list.html" class="sidebar-item">计划管理</a></li>
						<li><a href="/greenhouse/InputType/list.html" class="sidebar-item">投入类别管理</a></li>
						<li><a href="/greenhouse/Input/list.html" class="sidebar-item">投入管理</a></li>
						<li><a href="/greenhouse/Order/list.html" class="sidebar-item">订单管理</a></li>
						<li><a href="/greenhouse/Employee/list.html" class="sidebar-item">员工管理</a></li>
					</ul>
				</div>

				<div class="content">
					<h2 class="management-title">投入管理</h2>

					<!-- 查询条件 -->
					<div class="flex gap-4 mb-6">
						<div class="dropdown w-48">
							<button class="dropdown-button" @click="showPlanDropdown = !showPlanDropdown">
								计划名称：{{ selectedPlanName || '请选择' }}
								<i class="fa-solid fa-chevron-down ml-2"></i>
							</button>
							<div class="dropdown-content" v-show="showPlanDropdown">
								<div class="dropdown-item" v-for="plan in plans" :key="plan.id"
									@click="selectPlan(plan)">
									{{ plan.name }}
								</div>
							</div>
						</div>

						<div class="dropdown w-48" v-if="queryParam.planId">
							<button class="dropdown-button" @click="showGreenhouseDropdown = !showGreenhouseDropdown">
								大棚名称：{{ selectedGreenhouseName || '请选择' }}
								<i class="fa-solid fa-chevron-down ml-2"></i>
							</button>
							<div class="dropdown-content" v-show="showGreenhouseDropdown">
								<div class="dropdown-item" v-for="gh in getGreenhousesByPlanId(queryParam.planId)"
									:key="gh" @click="selectGreenhouse(gh)">
									{{ gh }}
								</div>
							</div>
						</div>

						<button class="button ml-2" @click="searchData">查询</button>
					</div>

					<!-- 添加按钮 -->
					<div class="mb-6">
						<button class="button" @click="openAddDialog">添加投入记录</button>
					</div>

					<!-- 数据表格 -->
					<table>
						<thead>
							<tr>
								<th>序号</th>
								<th>计划名称</th>
								<th>大棚名称</th>
								<th>批次</th>
								<th>投入时间</th>
								<th>总耗(万元)</th>
								<th>状态</th>
								<th>操作</th>
							</tr>
						</thead>
						<tbody>
							<tr v-for="(item, index) in filteredRecords" :key="item.id">
								<td>{{ index + 1 }}</td>
								<td>{{ item.planName }}</td>
								<td>{{ item.greenhouseName }}</td>
								<td>{{ item.batch || '-' }}</td>
								<td>{{ formatDate(item.investTime) }}</td>
								<td>{{ calculateTotalCost(item.id) }}</td>
								<td>{{ item.status }}</td>
								<td>
									<button v-if="item.status === '投入中'" class="button editButton mr-2"
										@click="openEditDialog(item)">
										编辑
									</button>

									<button v-if="item.status === '投入中'" class="button deleteButton mr-2"
										@click="deleteRecord(item.id)">
										删除
									</button>

									<button class="button" @click="openInvestDetailsDialog(item.id)">
										投入明细
									</button>
								</td>
							</tr>
						</tbody>
					</table>
				</div>
			</div>

			<!-- 添加/编辑对话框 -->
			<dialog ref="addEditDialog">
				<h2 class="text-lg font-bold text-neutral-800 mb-4 border-b border-neutral-200 pb-2">
					{{ isEdit ? '编辑投入记录' : '添加投入记录' }}
				</h2>
				<form class="space-y-4">
					<!-- 计划名称下拉菜单 -->
					<div class="dropdown">
						<button type="button" class="dropdown-button" @click="showPlanSelect = !showPlanSelect">
							计划名称：{{ selectedPlan.name || '请选择计划' }}
							<i class="fa-solid fa-chevron-down ml-2"></i>
						</button>
						<div class="dropdown-content" v-show="showPlanSelect">
							<div class="dropdown-item" v-for="plan in plans" :key="plan.id"
								@click="selectPlanForForm(plan)">
								{{ plan.name }}
							</div>
						</div>
					</div>

					<!-- 大棚名称下拉菜单 -->
					<div class="dropdown">
						<button type="button" class="dropdown-button"
							@click="selectedPlan.id && (showGreenhouseDropdown = !showGreenhouseDropdown)"
							:disabled="!selectedPlan.id">
							大棚名称：{{ selectedGreenhouse.name || '请选择大棚' }}
							<i class="fa-solid fa-chevron-down ml-2"></i>
						</button>
						<div class="dropdown-content" v-show="showGreenhouseDropdown && selectedPlan.id">
							<div class="dropdown-item" v-for="gh in selectedPlan.greenhouses" :key="gh"
								@click="selectGreenhouse(gh)">
								{{ gh }}
							</div>
						</div>
					</div>

					<!-- 批次输入框（修改为输入框） -->
					<div>
						<label class="block text-sm font-medium text-neutral-700 mb-1">批次</label>
						<input type="text" v-model="selectedBatch"
							class="w-full px-3 py-2 border border-neutral-300 rounded-md" placeholder="输入批次信息">
					</div>

					<!-- 投入时间 -->
					<div>
						<label class="block text-sm font-medium text-neutral-700 mb-1">投入时间</label>
						<input type="date" v-model="investTime"
							class="w-full px-3 py-2 border border-neutral-300 rounded-md">
					</div>

					<!-- 状态下拉菜单 -->
					<div class="dropdown">
						<button type="button" class="dropdown-button" @click="showStatusDropdown = !showStatusDropdown">
							状态：{{ selectedStatus }}
							<i class="fa-solid fa-chevron-down ml-2"></i>
						</button>
						<div class="dropdown-content" v-show="showStatusDropdown">
							<div class="dropdown-item" v-for="status in statusOptions" :key="status"
								@click="selectedStatus = status; showStatusDropdown = false">
								{{ status }}
							</div>
						</div>
					</div>

					<div class="flex justify-end space-x-2 mt-4">
						<button type="button" class="button" @click="saveRecord">{{ isEdit ? '保存修改' : '添加记录' }}</button>
						<button type="button" class="button bg-neutral-600" @click="closeDialog">取消</button>
					</div>
				</form>
			</dialog>

			<!-- 投入明细对话框 -->
			<dialog ref="investDetailsDialog">
				<h2 class="text-lg font-bold text-neutral-800 mb-4 border-b border-neutral-200 pb-2">
					投入明细 - {{ currentRecord.planName }} - {{ currentRecord.greenhouseName }}
					<span v-if="currentRecord.batch"> - 批次: {{ currentRecord.batch }}</span>
				</h2>

				<div class="mb-4 flex justify-between">
					<button class="button" @click="openAddInvestDetailDialog">添加投入明细</button>
					<button v-if="investDetails.some(d => d.status === '投入中')" class="button investButton"
						@click="completeAllInvestDetails">
						全部完成投入
					</button>
				</div>

				<div class="mb-4 bg-neutral-100 p-4 rounded-lg">
					<div class="grid grid-cols-2 gap-4">
						<div>
							<span class="text-sm text-neutral-600">计划名称:</span>
							<span class="font-medium">{{ currentRecord.planName }}</span>
						</div>
						<div>
							<span class="text-sm text-neutral-600">大棚名称:</span>
							<span class="font-medium">{{ currentRecord.greenhouseName }}</span>
						</div>
						<div>
							<span class="text-sm text-neutral-600">投入时间:</span>
							<span class="font-medium">{{ formatDate(currentRecord.investTime) }}</span>
						</div>
						<div>
							<span class="text-sm text-neutral-600">批次:</span>
							<span class="font-medium">{{ currentRecord.batch || '-' }}</span>
						</div>
					</div>
				</div>

				<table class="mb-4">
					<thead>
						<tr>
							<th>投入分类</th>
							<th>投入详情</th>
							<th>投入资金(万元)</th>
							<th>状态</th>
							<th>操作</th>
						</tr>
					</thead>
					<tbody>
						<tr v-for="(detail, index) in investDetails" :key="index">
							<td>{{ detail.category }}</td>
							<td>{{ detail.description || '-' }}</td>
							<td>{{ detail.amount.toFixed(2) }}</td>
							<td>{{ detail.status }}</td>
							<td>
								<button v-if="detail.status === '投入中'" class="button editButton mr-2"
									@click="openEditInvestDetailDialog(detail, index)">
									编辑
								</button>

								<button v-if="detail.status === '投入中'" class="button deleteButton"
									@click="deleteInvestDetail(index)">
									删除
								</button>

								<button v-if="detail.status === '投入中'" class="button investButton ml-2"
									@click="completeInvestDetail(index)">
									完成投入
								</button>

								<button v-else class="button investedButton ml-2" disabled>
									已投入
								</button>
							</td>
						</tr>
					</tbody>
				</table>

				<div class="text-right font-bold">
					投资总额: {{ calculateTotalCost(currentRecord.id) }} 万元
				</div>

				<div class="flex justify-end space-x-2 mt-4">
					<button type="button" class="button bg-neutral-600" @click="closeInvestDetailsDialog">关闭</button>
				</div>
			</dialog>

			<!-- 添加/编辑投入明细对话框 -->
			<dialog ref="investDetailDialog">
				<h2 class="text-lg font-bold text-neutral-800 mb-4 border-b border-neutral-200 pb-2">
					{{ isEditInvestDetail ? '编辑投入明细' : '添加投入明细' }}
				</h2>
				<form class="space-y-4">
					<!-- 投入分类下拉菜单 -->
					<div class="dropdown">
						<button type="button" class="dropdown-button"
							@click="showCategoryDropdown = !showCategoryDropdown">
							投入分类：{{ selectedCategory || '请选择分类' }}
							<i class="fa-solid fa-chevron-down ml-2"></i>
						</button>
						<div class="dropdown-content" v-show="showCategoryDropdown">
							<div class="dropdown-item" v-for="category in categoryOptions" :key="category"
								@click="selectCategory(category)">
								{{ category }}
							</div>
						</div>
					</div>

					<!-- 投入详情 -->
					<div>
						<label class="block text-sm font-medium text-neutral-700 mb-1">投入详情</label>
						<textarea v-model="investDescription" rows="3"
							class="w-full px-3 py-2 border border-neutral-300 rounded-md"></textarea>
					</div>

					<!-- 投入资金 -->
					<div>
						<label class="block text-sm font-medium text-neutral-700 mb-1">投入资金(万元)</label>
						<input type="number" v-model="investAmount"
							class="w-full px-3 py-2 border border-neutral-300 rounded-md" step="0.01">
					</div>

					<!-- 状态下拉菜单 -->
					<div class="dropdown">
						<button type="button" class="dropdown-button"
							@click="showDetailStatusDropdown = !showDetailStatusDropdown">
							状态：{{ selectedDetailStatus }}
							<i class="fa-solid fa-chevron-down ml-2"></i>
						</button>
						<div class="dropdown-content" v-show="showDetailStatusDropdown">
							<div class="dropdown-item" v-for="status in statusOptions" :key="status"
								@click="selectedDetailStatus = status; showDetailStatusDropdown = false">
								{{ status }}
							</div>
						</div>
					</div>

					<div class="flex justify-end space-x-2 mt-4">
						<button type="button" class="button"
							@click="saveInvestDetail">{{ isEditInvestDetail ? '保存修改' : '添加明细' }}</button>
						<button type="button" class="button bg-neutral-600" @click="closeInvestDetailDialog">取消</button>
					</div>
				</form>
			</dialog>

			<script>
				const {
					createApp,
					ref,
					reactive,
					computed
				} = Vue;

				createApp({
					setup() {
						// 模拟计划数据
						const plans = ref([{
								id: 1,
								name: '春季种植计划',
								greenhouses: ['A区3排7号大棚', 'B区2排5号大棚', 'C区5排2号大棚']
							},
							{
								id: 2,
								name: '夏季育苗计划',
								greenhouses: ['A区1排3号大棚', 'B区1排4号大棚', 'C区3排1号大棚']
							},
							{
								id: 3,
								name: '秋季增产计划',
								greenhouses: ['A区2排6号大棚', 'B区4排3号大棚', 'C区2排4号大棚']
							}
						]);

						// 模拟投入记录数据
						const records = ref([{
								id: 1,
								planId: 1,
								planName: '春季种植计划',
								greenhouseId: 'A区3排7号大棚',
								greenhouseName: 'A区3排7号大棚',
								investTime: '2025-05-01',
								status: '投入中',
								batch: '第一批'
							},
							{
								id: 2,
								planId: 1,
								planName: '春季种植计划',
								greenhouseId: 'B区2排5号大棚',
								greenhouseName: 'B区2排5号大棚',
								investTime: '2025-05-02',
								status: '已完成',
								batch: '第一批'
							},
							{
								id: 3,
								planId: 2,
								planName: '夏季育苗计划',
								greenhouseId: 'A区1排3号大棚',
								greenhouseName: 'A区1排3号大棚',
								investTime: '2025-05-03',
								status: '投入中',
								batch: '第一批'
							}
						]);

						// 模拟投入明细数据
						const allInvestDetails = ref([{
								recordId: 1,
								details: [{
										category: '种子',
										amount: 0.5,
										status: '已完成',
										description: '购买番茄、黄瓜种子'
									},
									{
										category: '肥料',
										amount: 0.8,
										status: '投入中',
										description: '有机肥料'
									},
									{
										category: '人工',
										amount: 1.0,
										status: '投入中',
										description: '播种人工费用'
									}
								]
							},
							{
								recordId: 2,
								details: [{
										category: '设施与设备',
										amount: 1.2,
										status: '已完成',
										description: '温控设备升级'
									},
									{
										category: '工具',
										amount: 0.3,
										status: '已完成',
										description: '灌溉工具'
									}
								]
							},
							{
								recordId: 3,
								details: [{
										category: '药剂',
										amount: 0.7,
										status: '投入中',
										description: '防虫药剂'
									},
									{
										category: '运输',
										amount: 0.5,
										status: '投入中',
										description: '种子运输费用'
									}
								]
							}
						]);

						// 查询参数
						const queryParam = reactive({
							planId: null,
							greenhouseName: ''
						});

						// 当前选中的大棚名称（用于查询）
						const selectedGreenhouseName = ref('');

						// 对话框状态
						const addEditDialog = ref(null);
						const investDetailsDialog = ref(null);
						const investDetailDialog = ref(null);

						const isEdit = ref(false);
						const isEditInvestDetail = ref(false);
						const currentEditId = ref(null);
						const currentRecord = ref({});
						const currentInvestDetailIndex = ref(null);

						// 下拉框状态
						const showPlanDropdown = ref(false);
						const showPlanSelect = ref(false);
						const showGreenhouseDropdown = ref(false);
						const showStatusDropdown = ref(false);
						const showCategoryDropdown = ref(false);
						const showDetailStatusDropdown = ref(false);

						// 选择项
						const selectedPlan = ref({});
						const selectedGreenhouse = ref({
							name: ''
						});
						const selectedStatus = ref('投入中');
						const selectedCategory = ref('');
						const selectedDetailStatus = ref('投入中');
						const selectedBatch = ref(''); // 批次改为自由输入，初始为空
						const investAmount = ref(0);
						const investDescription = ref('');

						// 投入时间
						const investTime = ref(new Date().toISOString().split('T')[0]);

						// 选项列表
						const statusOptions = ['投入中', '已完成'];
						const categoryOptions = ['设施与设备', '种子', '肥料', '工具', '药剂', '人工', '运输'];

						// 当前显示的投入明细
						const investDetails = ref([]);

						// 计算属性
						const selectedPlanName = computed(() => {
							if (!queryParam.planId) return '';
							const plan = plans.value.find(p => p.id === queryParam.planId);
							return plan ? plan.name : '';
						});

						const filteredRecords = computed(() => {
							let filtered = [...records.value];

							if (queryParam.planId) {
								filtered = filtered.filter(item => item.planId === queryParam.planId);
							}

							if (queryParam.greenhouseName) {
								filtered = filtered.filter(item =>
									item.greenhouseName.includes(queryParam.greenhouseName)
								);
							}

							return filtered;
						});

						// 方法
						const calculateTotalCost = (recordId) => {
							const recordDetails = allInvestDetails.value.find(item => item.recordId === recordId);
							if (!recordDetails) return '0.00';

							return recordDetails.details.reduce((sum, detail) => sum + detail.amount, 0).toFixed(2);
						};

						const selectPlan = (plan) => {
							queryParam.planId = plan.id;
							selectedGreenhouseName.value = '';
							showPlanDropdown.value = false;
						};

						const selectPlanForForm = (plan) => {
							selectedPlan.value = plan;
							selectedGreenhouse.value = {
								name: ''
							};
							showPlanSelect.value = false;
							showGreenhouseDropdown.value = false;
						};

						const selectGreenhouse = (gh) => {
							if (queryParam.planId) {
								selectedGreenhouseName.value = gh;
								queryParam.greenhouseName = gh;
							} else {
								selectedGreenhouse.value = {
									name: gh
								};
							}
							showGreenhouseDropdown.value = false;
						};

						const selectCategory = (category) => {
							selectedCategory.value = category;
							showCategoryDropdown.value = false;
						};

						// 根据计划ID获取大棚列表
						const getGreenhousesByPlanId = (planId) => {
							const plan = plans.value.find(p => p.id === planId);
							return plan ? plan.greenhouses : [];
						};

						const searchData = () => {
							// 实际应用中这里应该是API调用
						};

						// 主记录操作
						const openAddDialog = () => {
							isEdit.value = false;
							selectedPlan.value = {};
							selectedGreenhouse.value = {
								name: ''
							};
							selectedStatus.value = '投入中';
							investTime.value = new Date().toISOString().split('T')[0];
							currentEditId.value = null;
							selectedBatch.value = ''; // 批次初始为空
							addEditDialog.value.showModal();
						};

						const openEditDialog = (item) => {
							isEdit.value = true;
							selectedPlan.value = plans.value.find(p => p.id === item.planId) || {};
							selectedGreenhouse.value = {
								name: item.greenhouseName
							};
							selectedStatus.value = item.status;
							investTime.value = item.investTime;
							currentEditId.value = item.id;
							selectedBatch.value = item.batch || ''; // 批次初始为记录中的值或空
							addEditDialog.value.showModal();
						};

						const saveRecord = () => {
							if (!selectedPlan.value.id || !selectedGreenhouse.value.name) {
								alert('请选择计划和大棚');
								return;
							}

							const recordData = {
								planId: selectedPlan.value.id,
								planName: selectedPlan.value.name,
								greenhouseId: selectedGreenhouse.value.name,
								greenhouseName: selectedGreenhouse.value.name,
								investTime: investTime.value,
								status: selectedStatus.value,
								batch: selectedBatch.value // 使用输入的批次
							};

							if (isEdit.value && currentEditId.value) {
								const index = records.value.findIndex(item => item.id === currentEditId.value);
								if (index !== -1) {
									records.value[index] = {
										...records.value[index],
										...recordData
									};
								}
							} else {
								const newRecord = {
									id: Date.now(),
									...recordData
								};
								records.value.push(newRecord);

								// 为新记录创建空的投入明细
								allInvestDetails.value.push({
									recordId: newRecord.id,
									details: []
								});
							}

							closeDialog();
						};

						const deleteRecord = (id) => {
							if (confirm('确定要删除这条记录吗？')) {
								records.value = records.value.filter(item => item.id !== id);
								allInvestDetails.value = allInvestDetails.value.filter(item => item.recordId !== id);
							}
						};

						// 投入明细操作
						const openInvestDetailsDialog = (recordId) => {
							const record = records.value.find(item => item.id === recordId);
							if (record) {
								currentRecord.value = {
									...record
								};

								const details = allInvestDetails.value.find(item => item.recordId === recordId);
								investDetails.value = details ? [...details.details] : [];

								investDetailsDialog.value.showModal();
							}
						};

						const closeInvestDetailsDialog = () => {
							investDetailsDialog.value.close();
						};

						const openAddInvestDetailDialog = () => {
							isEditInvestDetail.value = false;
							selectedCategory.value = '';
							investAmount.value = 0;
							selectedDetailStatus.value = '投入中';
							investDescription.value = '';
							currentInvestDetailIndex.value = null;
							investDetailDialog.value.showModal();
						};

						const openEditInvestDetailDialog = (detail, index) => {
							isEditInvestDetail.value = true;
							selectedCategory.value = detail.category;
							investAmount.value = detail.amount;
							selectedDetailStatus.value = detail.status;
							investDescription.value = detail.description || '';
							currentInvestDetailIndex.value = index;
							investDetailDialog.value.showModal();
						};

						const saveInvestDetail = () => {
							if (!selectedCategory.value || !investAmount.value) {
								alert('请填写完整信息');
								return;
							}

							const detail = {
								category: selectedCategory.value,
								amount: parseFloat(investAmount.value),
								status: selectedDetailStatus.value,
								description: investDescription.value
							};

							if (isEditInvestDetail.value && currentInvestDetailIndex.value !== null) {
								investDetails.value[currentInvestDetailIndex.value] = detail;
							} else {
								investDetails.value.push(detail);
							}

							// 更新总数据
							const detailsIndex = allInvestDetails.value.findIndex(item => item.recordId ===
								currentRecord.value.id);
							if (detailsIndex !== -1) {
								allInvestDetails.value[detailsIndex].details = [...investDetails.value];
							} else {
								allInvestDetails.value.push({
									recordId: currentRecord.value.id,
									details: [...investDetails.value]
								});
							}

							// 检查是否所有明细都已完成，如果是则更新主记录状态
							checkAndUpdateRecordStatus();

							closeInvestDetailDialog();
						};

						const deleteInvestDetail = (index) => {
							if (confirm('确定要删除这条明细吗？')) {
								investDetails.value.splice(index, 1);

								// 更新总数据
								const detailsIndex = allInvestDetails.value.findIndex(item => item.recordId ===
									currentRecord.value.id);
								if (detailsIndex !== -1) {
									allInvestDetails.value[detailsIndex].details = [...investDetails.value];
								}

								// 检查是否所有明细都已完成，如果是则更新主记录状态
								checkAndUpdateRecordStatus();
							}
						};

						const completeInvestDetail = (index) => {
							investDetails.value[index].status = '已完成';

							// 更新总数据
							const detailsIndex = allInvestDetails.value.findIndex(item => item.recordId ===
								currentRecord.value.id);
							if (detailsIndex !== -1) {
								allInvestDetails.value[detailsIndex].details = [...investDetails.value];
							}

							// 检查是否所有明细都已完成，如果是则更新主记录状态
							checkAndUpdateRecordStatus();
						};

						// 完成所有投入明细
						const completeAllInvestDetails = () => {
							if (confirm('确定要完成所有投入明细吗？完成后将无法修改。')) {
								// 将所有明细状态设为已完成
								investDetails.value.forEach(detail => {
									detail.status = '已完成';
								});

								// 更新总数据
								const detailsIndex = allInvestDetails.value.findIndex(item => item.recordId ===
									currentRecord.value.id);
								if (detailsIndex !== -1) {
									allInvestDetails.value[detailsIndex].details = [...investDetails.value];
								}

								// 更新主记录状态
								const recordIndex = records.value.findIndex(item => item.id === currentRecord.value.id);
								if (recordIndex !== -1) {
									records.value[recordIndex].status = '已完成';
								}

								alert('所有投入明细已完成！');
							}
						};

						// 检查并更新主记录状态
						const checkAndUpdateRecordStatus = () => {
							const details = allInvestDetails.value.find(item => item.recordId === currentRecord.value
								.id);
							if (!details) return;

							// 检查所有明细是否都已完成
							const allCompleted = details.details.every(detail => detail.status === '已完成');

							// 如果所有明细都已完成，则更新主记录状态
							if (allCompleted && currentRecord.value.status === '投入中') {
								const recordIndex = records.value.findIndex(item => item.id === currentRecord.value.id);
								if (recordIndex !== -1) {
									records.value[recordIndex].status = '已完成';
								}
							}
						};

						const closeInvestDetailDialog = () => {
							investDetailDialog.value.close();
						};

						const closeDialog = () => {
							addEditDialog.value.close();
							showPlanSelect.value = false;
							showGreenhouseDropdown.value = false;
							showStatusDropdown.value = false;
						};

						const formatDate = (dateStr) => {
							return new Date(dateStr).toLocaleDateString();
						};

						return {
							plans,
							records,
							allInvestDetails,
							queryParam,
							selectedPlanName,
							filteredRecords,
							isEdit,
							isEditInvestDetail,
							addEditDialog,
							investDetailsDialog,
							investDetailDialog,
							showPlanDropdown,
							showPlanSelect,
							showGreenhouseDropdown,
							showStatusDropdown,
							showCategoryDropdown,
							showDetailStatusDropdown,
							selectedPlan,
							selectedGreenhouse,
							selectedStatus,
							selectedCategory,
							selectedDetailStatus,
							selectedBatch,
							investAmount,
							investDescription,
							currentRecord,
							investDetails,
							statusOptions,
							categoryOptions,
							calculateTotalCost,
							selectPlan,
							selectPlanForForm,
							selectGreenhouse,
							selectCategory,
							getGreenhousesByPlanId,
							searchData,
							openAddDialog,
							openEditDialog,
							saveRecord,
							deleteRecord,
							openInvestDetailsDialog,
							closeInvestDetailsDialog,
							openAddInvestDetailDialog,
							openEditInvestDetailDialog,
							saveInvestDetail,
							deleteInvestDetail,
							completeInvestDetail,
							completeAllInvestDetails,
							closeInvestDetailDialog,
							closeDialog,
							formatDate,
							investTime,
							selectedGreenhouseName
						};
					}
				}).mount('#app');
			</script>
		</div>
	</body>
</html>